<template>
    <div>
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple-light">
            <list-layout>
              <div slot="search">
                <el-form :model="queryParams" :inline="true" ref="queryForm" v-show="showSearch" label-width="120px">
                  <el-row>
                    <el-col :span="6">
                      <!--            物料编号-->
                      <el-form-item :label="$t('inventoryManagement.materialNo')" prop="materialCode">
                        <el-input v-model="queryParams.materialCode"
                                  :placeholder="$t('public.placeholder',{placeholder: $t('inventoryManagement.inventoryManagement')})"
                                  size="small" @keyup.enter.native="handleQuery"/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <!--    物料描述    -->
                      <el-form-item label="物料描述" prop="materialName">
                        <el-input v-model="queryParams.materialName"
                                  :placeholder="$t('public.placeholder',{placeholder: '物料描述'})"
                                  size="small" @keyup.enter.native="handleQuery"/>
                      </el-form-item>
                    </el-col>
                    <!--    是否已绑定    -->
                    <el-col :span="12">
                      <el-form-item label="是否已绑定" prop="exempted">
                        <el-select v-model="queryParams.isBind" style="width:100%;" clearable size="small">
                          <el-option key="0" :label="$t('public.no')" value="0"/>
                          <el-option key="1" :label="$t('public.yes')" value="1"/>
                          <el-option key="" label="全部" value=""/>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <!--    事业部    -->
                    <el-col :span="12">
                      <el-form-item :label="$t('inspectionStandards.division')" prop="divisionName">
                        <division-dialog v-model="queryParams.divisionName"  />
                      </el-form-item>
                    </el-col>

                    <el-col :span="24" align="center">
                      <el-form-item class="right-btns">
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
                          {{ $t('public.query') }}
                        </el-button>
                        <el-button icon="el-icon-refresh" class="resectBtn" size="mini" @click="resetQuery">
                          {{ $t('public.reset') }}
                        </el-button>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>

              </div>
              <div class="app-container">
                <el-row :gutter="10" class="table-action-wrap btnGroup">
                  <el-col :span="1.5">
                    <el-button icon="el-icon-paperclip" size="mini" class="deleteitemBtn" @click="handleApproval('typeMaterialBind')"
                               v-hasPermi="['ny-iqc:project:remove']">批量{{ $t('public.bind') }}
                    </el-button>
                    <el-button icon="el-icon-paperclip" size="mini" @click="handleApproval('release')"
                               v-hasPermi="['ny-iqc:project:remove']">批量解绑
                    </el-button>
                  </el-col>
                </el-row>
                <div class="container-table">
                  <el-table :height="tableHeight" border stripe v-loading="loading" :data="typeList"
                            @selection-change="handleSelectionChange">

                    <el-table-column type="selection" width="55" align="center"/>
                    <!--          序号-->
                    <el-table-column :label="$t('public.serialNum')" type="index" width="55" align="center"/>
                    <!--          物料编号-->
                    <el-table-column :label="$t('basicData.materialNo')" align="left" prop="materialCode"/>
                    <!--          物料描述-->
                    <el-table-column label="物料描述" align="left" prop="materialName"
                                     minWidth="160"/>
                    <!--          所属厂区-->
                    <el-table-column :label="$t('formValidation.affiliatedFactoryArea')" align="left" prop="factoryName"
                                     minWidth="160"/>
                    <!--          事业部-->
                    <el-table-column :label="$t('inspectionManagement.ssDivision')" align="center" min-width="100" prop="divisionName" />
                    <!--        是否已经绑定  -->
                    <el-table-column label="是否已经绑定" align="left" prop="isBind" minWidth="160"
                                     show-overflow-tooltip>
                      <template slot-scope="scope">
                        <span>{{ convert(scope.row) }}</span>
                      </template>
                    </el-table-column>
                    <!--          绑定大类-->
                    <el-table-column label="绑定大类" align="left" prop="categoryName" minWidth="160"/>
                    <el-table-column :label="$t('public.opera')" fixed="right" align="center" width="160">
                      <template slot-scope="scope">
                        <el-button icon="el-icon-paperclip" size="mini" class="deleteitemBtn" @click="handleApproval('typeMaterialBind',scope.row)"
                               v-hasPermi="['ny-iqc:project:remove']">{{ $t('public.bind') }}
                        </el-button>
                        <el-button icon="el-icon-paperclip" size="mini" @click="handleApproval('release',scope.row)"
                                  v-hasPermi="['ny-iqc:project:remove']">解绑
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>

                  <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                              :limit.sync="queryParams.pageSize" @pagination="getListTypes"
                              layout="total, sizes, prev, pager, next, jumper"/>
                </div>
              </div>
            </list-layout>
          </div>
        </el-col>
      </el-row>
      <el-dialog
        title="绑定分类"
        :visible.sync="bindCategoryDialogVisible"
        width="30%"
        @close="bindCategoryDialogVisible = false"
    >
        <div class="block">
        <span style="display: block;" class="demonstration">请选择绑定分类，绑定后，该物料会获取当前绑定的节点下所有物料号的检验数据</span>
        <el-cascader
            ref="cascader"
            :options="data"
            :props="{ expandTrigger:'click',emitPath:false,checkStrictly: true,value:'id',label:'label' }"
            clearable
            @change="cascaderChange"
        ></el-cascader>
        </div>
        <div slot="footer" class="dialog-footer">
        <el-button @click="bindCategoryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="bindCategory">保存</el-button>
        </div>
    </el-dialog>
    <el-dialog
        title="解绑分类"
        :visible.sync="releaseCategoryDialogVisible"
        width="30%"
        @close="releaseCategoryDialogVisible = false"
    >
        <div class="block">
        <span style="display: block;" class="demonstration">解绑之后，该物料的检验任务将不允许获取其他基地的共享数据，确定解绑吗？</span>
        </div>
        <div slot="footer" class="dialog-footer">
        <el-button @click="releaseCategoryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="releaseCategory">确定</el-button>
        </div>
    </el-dialog>
    </div>
  </template>

  <script>
  import {refreshCache,} from '@/api/basic/dict/type'
  import {getToken} from '@/utils/auth'
  import {mapState} from 'vuex'
  import {
    // getTree,
    getTreeOld,
    addTreeNode,
    updTreeNode,
    delTreeNode,
    editBind
  } from '@/api/basic/materialClassification'
  import {
    getListTypes,
    typeMaterialBind,
    unBinding
  } from '@/api/basic/typeMaterial'
  import importDialog from "../../components/importDialog/index.vue";
  import DivisionDialog from '@/views/components/DivisionDialog'


  export default {
    name: 'auditProject',
    components: {
      importDialog,
      DivisionDialog
    },

    data() {
      const data = [];
      return {
        tempMId:'',
        showBtnFlag: false,
        currentBindCategory: '',
        createCategoryDialogVisible: false,
        editItemDialogVisible: false,
        editCategoryDialogVisible: false,
        appendCategoryDialogVisible: false,
        bindCategoryDialogVisible: false,
        releaseCategoryDialogVisible: false,
        templateVisible: false,
        newCategoryName: {
          name: '',
        },
        editItem: {},
        editCategoryName: {
          name: '',
        },
        appendCategoryName: {
          name: '',
        },
        bindCategoryName: {
          name: '',
        },
        data: JSON.parse(JSON.stringify(data)),
        dialogType: 1, //1:新增  2：编辑 3：查看
        auditProjectVisible: false,
        dialogForm: {},
        deviceOptions: [],
        factoryOptions: [],
        direction: 'rtl',
        addInspection: false,
        visible: false,
        drawer: false,
        approvalOpen: false,
        viewModel: {
          inspectionInformation: '0',
        },
        editModel: {
          inspectionInformation: '0',
        },
        approvalForm: {
          status: '1',
          textarea: '',
        },
        selBtn: 1,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 字典表格数据
        typeList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        tableHeight: 'calc(100vh - 308px)',
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 20,
          materialCode: '',
          materialName: '',
          isBind: '',
          categoryId: ''
        },
        // bind参数
        bindParams: {
          categoryId: '',
          categoryName: '',
          materialCategorys: [],
        },
        // 表单参数
        form: undefined,
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: '检验项目导入',
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {Authorization: 'Bearer ' + getToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + '/ny-iqc/project/import',
        },
        fullscreen: false,
        names: [],
      }
    },
    created() {
      this.getTreeList()
      this.getListTypes()

    },
    computed: {
      ...mapState({
        isFold: (state) => state.app.isFold,
      }),
    },
    watch: {
      isFold(val) {
        if (val === true) {
          this.tableHeight = 'calc(100vh - 308px)'
        } else {
          this.tableHeight = 'calc(100vh - 396px)'
        }
      },
    },
    methods: {
      handleImport() {
        this.templateVisible = true
      },
      handleExportList(templateFlag) {
        this.download(
            'qcmasterdata/category/export/',
            {
              template: templateFlag,
            },
            `type_${new Date().getTime()}.xlsx`
        )
      },
      convert(data) {
        if (data.isBind == '1') {
          return '是'
        }
        return '否'
      },
      handleRightClick() {
        this.showBtnFlag = true
      },
      handleNodeClick(data) {
        this.queryParams.categoryId = data.id;
        this.queryParams.isBind = '1';
        this.getListTypes()
      },
      createCategory() {
        // 获取用户输入的分类名称
        const categoryName = this.newCategoryName.name.trim();

        // 检查分类名称是否为空
        if (!categoryName) {
          this.$message.error('分类名称不能为空');
          return;
        }
        addTreeNode({delFlag: '0', parentId: '0', label: categoryName}).then((response) => {
          this.$modal.msgSuccess('新增成功')
          this.getTreeList();
        })
        // 清空输入框并关闭对话框
        this.newCategoryName.name = '';
        this.createCategoryDialogVisible = false;
      },

      appendCategory() {
        // 获取用户输入的分类名称
        const categoryName = this.appendCategoryName.name.trim();
        const parentId = this.appendCategoryName.parentId.trim();

        // 检查分类名称是否为空
        if (!categoryName) {
          this.$message.error('分类名称不能为空');
          return;
        }
        // 将新的一级分类添加到 categories 数组中
        // this.categories.push(newCategory);
        addTreeNode({delFlag: '0', parentId: parentId, label: categoryName}).then((response) => {
          this.$modal.msgSuccess('新增成功')
          this.getTreeList();
        })
        // 清空输入框并关闭对话框
        this.appendCategoryName.name = '';
        this.appendCategoryDialogVisible = false;
      },
      cascaderChange() {
        let checkedNodes = this.$refs['cascader'].getCheckedNodes();
        this.bindParams.categoryId = checkedNodes[0].data.id
        this.bindParams.categoryName = checkedNodes[0].pathNodes.map(node => node.label).join('/');
      },
      bindCategory() {
        this.queryParams.isBind = ''
        this.queryParams.categoryId = ''
        typeMaterialBind(this.bindParams).then((response) => {
          if (response.code == 200) {
            this.$modal.msgSuccess('绑定成功')
            this.getListTypes()
          }
        })
        // 清空输入框并关闭对话框
        this.bindCategoryDialogVisible = false;
      },
      releaseCategory(){
        let ids = this.bindParams.materialCategorys.map(item => {
          return item.materialCode ? item.materialCode : ''
        })
        unBinding(ids.toString()).then((response) => {
          if (response.code == 200) {
            this.$modal.msgSuccess('解绑成功')
            this.getListTypes()
          }
        })
        // 清空输入框并关闭对话框
        this.releaseCategoryDialogVisible = false;
      },
      editItemSava() {
        this.queryParams.isBind = ''
        this.queryParams.categoryId = ''
        this.editItem.categoryId = this.bindParams.categoryId
        this.editItem.categoryName = this.bindParams.categoryName
        editBind(this.editItem).then((response) => {
          if (response.code == 200) {
            this.$modal.msgSuccess('绑定成功')
            this.getListTypes()
          }
          this.editItemDialogVisible = false
        })
        // 清空输入框并关闭对话框
        this.bindCategoryDialogVisible = false;
      },

      editCategory() {
        // 获取用户输入的分类名称
        const id = this.editCategoryName.id.trim();
        const categoryName = this.editCategoryName.name.trim();

        // 检查分类名称是否为空
        if (!categoryName) {
          this.$message.error('分类名称不能为空');
          return;
        }
        // 将新的一级分类添加到 categories 数组中
        // this.categories.push(newCategory);
        updTreeNode({id: id, label: categoryName}).then((response) => {
          this.$modal.msgSuccess(this.$t('formValidation.successfullyModified'))
          this.getTreeList();
        })
        // 清空输入框并关闭对话框
        this.editCategoryName.name = '';
        this.editCategoryDialogVisible = false;
      },
      showCreateCategoryDialog() {
        this.createCategoryDialogVisible = true;
      },
      showEditCategoryDialog() {
        this.editCategoryDialogVisible = true;
      },
      getTreeList() {
        getTreeOld("").then((response) => {
          this.data = response.data
        })
      },
      append(node, data) {
        this.appendCategoryName.parentId = data.id;
        this.appendCategoryDialogVisible = true
      },
      edit(data) {
        this.editCategoryName.name = data.label;
        this.editCategoryName.id = data.id;
        this.editCategoryDialogVisible = true
      },

      remove(data) {
        this.$modal
          .confirm(this.$t('确定删除该分类吗?'))
          .then(function () {

            return delTreeNode(data.id)
          })
          .then(() => {
            this.getTreeList()
            this.getListTypes()
            this.$modal.msgSuccess(this.$t('tips.deleteSuccess'))
          })
      },
      drawerClose() {
        this.drawer = false
      },
      uploadCallback() {
        this.getListTypes()
      },
      getListTypes() {
        this.loading = true
        let params = JSON.parse(JSON.stringify(this.queryParams))
        console.log(params)
        getListTypes(params).then((response) => {
          if (response.code == 200 && response.rows) {
            this.typeList = response.rows
            this.total = response.total
            this.loading = false
          }
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {}
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getListTypes()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams.isBind = ''
        this.queryParams.categoryId = ''
        this.resetForm('queryForm')
        this.handleQuery()
      },
      handleApproval(name,material) {
        if (this.bindParams.materialCategorys.length === 0 && !material) {
          this.$modal.msgWarning('请至少选择一条记录!')
          return
        }
        material ? this.bindParams.materialCategorys = [material] : ''
        name == 'typeMaterialBind' ? this.bindCategoryDialogVisible = true : this.releaseCategoryDialogVisible = true

      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.bindParams.materialCategorys = selection;
      },

      deviceRemoteMethod(e) {
        console.log(e)
        // listAllProjectMessage({deviceName:e}).then(res=>{
        //   this.deviceOptions = res.data
        // })
      },
      handleDeviceChange(e) {
        this.queryParams.deviceName = e.join(',')
      },
      handleProjectTypeChange(e) {
        this.queryParams.gaugeType = e.join(',')
      },
      /** 查看按钮操作 */
      handleView(row) {
        this.dialogType = 3
        this.form = row
        this.visible = true
        // if(row.hasRead == 0){
        //   readNotice(row.noticeId).then(res=>{
        //     if(res.code == 200){
        //       this.handleQuery()
        //     }
        //   })
        // }
      },
      /** 编辑按钮操作 */
      handleEdit(row) {
        this.editItem = row
        this.editItemDialogVisible = true
      },
      /** 关闭抽屉操作 */
      handleClose(row) {
        this.drawer = false
      },
      /** 下载模板操作 */
      importTemplate() {
        this.download(
          'system/saas/user/importTemplate',
          {},
          `user_template_${new Date().getTime()}.xlsx`
        )
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false
        this.upload.isUploading = false
        this.$refs.upload.clearFiles()
        this.$alert(response.msg, '导入结果', {
          dangerouslyUseHTMLString: true,
        })
        this.getListTypes()
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit()
      },
      /** 刷新缓存按钮操作 */
      handleRefreshCache() {
        refreshCache().then(() => {
          this.$modal.msgSuccess('刷新成功')
        })
      },
    },
  };
  </script>

  <style>
  ::v-deep .el-card {
    padding-top: 20px;
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
    padding-bottom: 20px;
  }

  ::v-deep .el-aside {
    padding: 0;
    margin-bottom: 0;
  }

  .content-style {
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 2px;
    background-color: white;
    margin-top: 10px;
  }

  ::v-deep .el-button-group .selBtn {
    background: #fff;
    border: 1px solid #0b7be3;
    color: #0b7be3;
  }

  ::v-deep .el-button-group .unselBtn {
    background: #fff;
    border: 1px solid #ededf2;
    color: #666666;
  }

  .header-left {
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333333;
    padding: 3px 0 10px;
    display: inline-flex;
    justify-content: center;
    border-bottom: 2px solid #0b7be3;
  }

  .header-right {
    float: right;
  }

  .container-header {
    border-bottom: 1px solid #ededf2;
  }

  .container-table {
    float: left;
  //margin-top:6px; width: 100%;
  }

  .mb8 {
    float: left;
    margin-top: 6px;
    width: 100%;
  }

  .drawer-footer {
    display: flex;
    position: relative;
    z-index: 9999;
    bottom: -40px;
    height: 40px;
    justify-content: center;
    width: 100%;
  }

  .drawer-close {
    background: #f7f8fa;
    border-color: #f7f8fa;
  }

  .right-btns ::v-deep .el-button {
    margin-top: 0;
  }

  .app-container {
    padding: 0;
  }

  .table-action-wrap {
    padding: 12px 0;
  }
  </style>
